package www.dianbaozu.com.ui.login

import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import www.dianbaozu.com.extension.nimFlow
import www.dianbaozu.com.extension.save
import www.wen.com.common.lib.base.module.BaseCountDownModel
import www.wen.com.common.lib.data.entities.*
import www.wen.com.common.lib.data.repository.AppDataManager
import www.wen.com.common.lib.extension.getString
import www.wen.com.common.lib.util.SpUtil


/**
 * @author WEN
 * @Description:绑定手机号ViewModel
 * @date 2020//25 17:48
 */
class BindPhoneViewModel @ViewModelInject constructor(appDataManager: AppDataManager) :
        BaseCountDownModel(appDataManager) {


//    fun requestBindPhone(
//            accessToken: String,
//            openId: String,
//            smsCode: String,
//            mobile: String,
//            action: () -> Unit,
//    ) {
//        viewModelScope.launch {
//            loading.value = UiStateCustom(
//                    stateData = LoadingDialog(
//                            getString(R.string.logging_in),
//                            LoadingDialogStateType.LOADING
//                    )
//            )
//            val result = appDataManager.requestRegisterByToken(
//                    RequestLoginOrRegisterByToken(accessToken = accessToken,
//                            openId = openId,
//                            smsCode = smsCode,
//                            mobile = mobile))
//            if (result is Result.Success) {
//                SpUtil.save(result.data.user)
//                SpUtil.save(result.data.token!!)
//                loading.value = UiStateCustom(
//                        stateData = LoadingDialog(
//                                tip = getString(R.string.successful_landing),
//                                loadingDialogStateType = LoadingDialogStateType.SUCCESS,
//                                isShowDialogTip = false,
//                                isShowToastTip = true,
//                                action = action
//                        )
//                )
//            } else if (result is Result.Error) {
//                loading.value = UiStateCustom(
//                        stateData = LoadingDialog(
//                                tip = result.exception.message ?: getString(R.string.failed_to_login),
//                                loadingDialogStateType = LoadingDialogStateType.ERROR,
//                                isShowDialogTip = false,
//                                isShowToastTip = true
//                        )
//                )
//            }
//        }
//    }

    var mLoginInfo: LoginInfo? = null


    /**
     * 验证码注册|登陆
     */
    @FlowPreview
    fun requestBindPhone(
            accessToken: String,
            openId: String,
            smsCode: String,
            mobile: String,
            action: (LoginInfo) -> Unit,
    ) {
        viewModelScope.launch {
            appDataManager.registerByTokenFlow(RequestLoginOrRegisterByToken(accessToken = accessToken,
                    openId = openId,
                    smsCode = smsCode,
                    mobile = mobile)
            )
                    .retryWhen { cause, attempt ->
                        return@retryWhen cause.message == "网络异常" && attempt <= 1
                    }
                    .flatMapConcat {
                        mLoginInfo = it.data

                        if (!it.data.user.forbidStatus) {
                            appDataManager.nimFlow(
                                    it.data.user.accId,
                                    it.data.user.accToken
                            ) {
                                SpUtil.save(it.data.user)
                                SpUtil.save(it.data.token!!)
                            }
                        } else {
                            throw Exception("账号被封禁")
                        }
                    }
                    .onStart {
                        loading.value = UiStateCustom(
                                stateData = LoadingDialog(
                                        getString(www.dianbaozu.com.R.string.logging_in),
                                        LoadingDialogStateType.LOADING
                                )
                        )
                    }
                    .onCompletion { cause ->
                        if (cause == null) {
                            loading.value = UiStateCustom(
                                    stateData = LoadingDialog(
                                            tip = getString(www.dianbaozu.com.R.string.successful_landing),
                                            loadingDialogStateType = LoadingDialogStateType.SUCCESS,
                                            isShowDialogTip = false,
                                            isShowToastTip = true
                                    )
                            )
                        }
                    }
                    .catch { cause ->
                        loading.value = UiStateCustom(
                                stateData = LoadingDialog(
                                        tip = cause.message ?: "网络异常",
                                        loadingDialogStateType = LoadingDialogStateType.ERROR,
                                        isShowDialogTip = false,
                                        isShowToastTip = (cause.message != null && cause.message != "账号被封禁")
                                )
                        )
                        mLoginInfo?.run { action.invoke(mLoginInfo!!) }
                    }
                    .collect {
                        mLoginInfo?.run { action.invoke(mLoginInfo!!) }
                    }
        }
    }


    override fun switchEnabledSubmit(textChange: CharSequence) {
        mEnabledSubmit.value =
                mPhone.value!!.isNotBlank() &&
                        mPhone.value!!.length >= 5 &&
                        mVerificationCode.value!!.isNotBlank()
    }

}


